<template>
  <div>
    <el-form ref="deptForm" label-width="120px">
      <el-form-item label="部门名称">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { addDepartments, getDepartDetail, updateDepartDetail } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
    }
  },
  created() {
    this.queryEdit()
  },
  methods: {
    hSubmit() {
      this.isEdit ? this.doEdit() : this.doAdd()
    },
    hCancel() {
      // 关闭弹层 重新渲染页面
      this.$emit('close')
    },
    // 新增部门
    async doAdd() {
      const datas = { ...this.form, pid: this.id }
      const res = await addDepartments(datas)
      console.log(res)
      // 清空数据
      this.form = {}
      // 关闭弹层 重新渲染页面
      this.$emit('close')
    },
    // 查询部门详情 编辑页面一打开数据回填
    async queryEdit() {
      if (this.isEdit) {
        const res = await getDepartDetail(this.id)
        console.log(res)
        this.form = res.data
      }
    },
    // 编辑好数据更新
    async doEdit() {
      await updateDepartDetail(this.form)

      // 关闭弹层 重新渲染页面
      this.$emit('close')
    }
  }
}
</script>
